<?php

namespace App\Http\Model\CoolNumberShoppingMall;

use App\Exceptions\PublicException;
use App\Http\Model\Base;
use Illuminate\Support\Facades\DB;

class UserScore extends Base
{
    /**
     * 表名字
     *
     * @var string
     */
    protected $table = 'cool_number_user_score';

    /**
     * 指示模型是否自动维护时间戳
     *
     * @var bool
     */
    public $timestamps = true;

    /**
     * 模型日期列的存储格式。
     *
     * @var string
     */
    protected $dateFormat = 'U';

    /**
     * 可以被批量赋值的属性。
     *
     * @var array
     */
    protected $fillable = ['id', 'user_id', 'score', 'created_at', 'updated_at'];

    /**
     * @param array $attributes
     */
    public function __construct(array $attributes = [])
    {
        parent::__construct($this->table, $attributes);
    }

    /**
     * 增加分数
     *
     * Created at 2021/12/6 13:33
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @param string $from 来源
     * @param int $score
     * @throws \App\Exceptions\PublicException
     * @throws \Throwable
     */
    public function inc(int $userId, string $from, int $score = 0)
    {
        try {
            $query = self::query()->where('user_id', $userId)->count();
            DB::beginTransaction();
            (new UserScoreStream())->add($userId, $from, $score);
            if (!$query) {
                self::query()->create(['user_id' => $userId, 'score' => $score]);
                DB::commit();
                return;
            }

            if ($score) {
                if ($score < 0) {
                    $affectRow = self::query()->where('user_id', $userId)->where('score', '>=', abs($score))
                        ->limit(1)->increment('score', $score);
                    if (!$affectRow) {
                        throw new PublicException('积分扣减失败，积分不足');
                    }
                } else {
                    self::query()->where('user_id', $userId)
                        ->limit(1)->increment('score', $score);
                }
            }

            DB::commit();
        } catch (\Throwable $exception) {
            DB::rollBack();
            throw $exception;
        }
    }

    /**
     * 获取用户的靓号积分
     *
     * Created at 2021/12/6 14:17
     * @Author <yuxiang.zhu@asiainnovations.net>
     * @param int $userId
     * @return int
     */
    public function getUserScore(int $userId): int
    {
        return intval(self::query()->where('user_id', $userId)->value('score'));
    }
}